<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use Exception;

class Yuncunchu extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 重写初始化方法，支持Bearer token
     */
    protected function _initialize()
    {
        // 支持Bearer token格式
        $authorization = $this->request->header('Authorization');
        if ($authorization && strpos($authorization, 'Bearer ') === 0) {
            $token = substr($authorization, 7); // 去掉 'Bearer ' 前缀
            $this->request->server(['HTTP_TOKEN' => $token]);
        }
        
        // 调用父类初始化
        parent::_initialize();
    }

    /**
     * 测试接口
     */
    public function test()
    {
        $this->success('云存储API工作正常');
    }

    /**
     * 上传文件到云存储
     */
    public function upload()
    {
        // 支持Bearer token验证
        $authorization = $this->request->header('Authorization');
        if ($authorization && strpos($authorization, 'Bearer ') === 0) {
            $token = substr($authorization, 7);
            $this->request->server(['HTTP_TOKEN' => $token]);
        }
        
        // 检查是否有用户信息（通过token）
        $user = null;
        if ($this->auth->isLogin()) {
            $user = $this->auth->getUserinfo();
        }
        $module = $this->request->post('module', 'scanwork'); // 模块名
        $action = $this->request->post('action', 'report'); // 操作名
        $configId = $this->request->post('config_id', null); // 配置ID，null表示使用默认配置
        
        if (!empty($_FILES['file'])) {
            $file = $_FILES['file'];
            
            if ($file['error'] == 0) {
                $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
                $allowExt = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'jfif'];
                if (!in_array(strtolower($ext), $allowExt)) {
                    $this->error('不支持的文件格式');
                }
                
                if ($file['size'] > 50 * 1024 * 1024) {
                    $this->error('文件大小不能超过50MB');
                }
                
                try {
                    // 添加详细日志
                    \think\Log::info('Yuncunchu API - 开始上传文件');
                    \think\Log::info('Yuncunchu API - 模块: ' . $module . ', 操作: ' . $action);
                    \think\Log::info('Yuncunchu API - 文件信息: ' . json_encode($file));
                    
                    // 直接处理文件上传，不依赖云存储服务
                    $uploadDir = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'scanwork' . DS . date('Y-m-d');
                    if (!is_dir($uploadDir)) {
                        mkdir($uploadDir, 0755, true);
                    }
                    
                    // 生成文件名
                    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
                    $fileName = uniqid() . '_' . $action . '.' . $extension;
                    $filePath = $uploadDir . DS . $fileName;
                    
                    // 移动文件
                    if (move_uploaded_file($file['tmp_name'], $filePath)) {
                        // 生成URL
                        $url = '/uploads/scanwork/' . date('Y-m-d') . '/' . $fileName;
                        
                        \think\Log::info('Yuncunchu API - 文件上传成功: ' . $url);
                        
                        $this->success('上传成功', [
                            'url' => $url,
                            'file_id' => null,
                            'file_name' => $fileName
                        ]);
                    } else {
                        \think\Log::error('Yuncunchu API - 文件移动失败');
                        $this->error('上传失败：文件保存失败');
                    }
                } catch (\Exception $e) {
                    \think\Log::error('Yuncunchu API - 异常: ' . $e->getMessage());
                    \think\Log::error('Yuncunchu API - 异常文件: ' . $e->getFile());
                    \think\Log::error('Yuncunchu API - 异常行号: ' . $e->getLine());
                    \think\Log::error('Yuncunchu API - 异常堆栈: ' . $e->getTraceAsString());
                    error_log('云存储API上传失败: ' . $e->getMessage());
                    $this->error('上传失败：' . $e->getMessage());
                }
            } else {
                $this->error('文件上传错误');
            }
        } else {
            $this->error('没有选择文件');
        }
    }

    /**
     * 批量上传文件到云存储
     */
    public function batchUpload()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $module = $this->request->post('module', 'scanwork'); // 模块名
        $action = $this->request->post('action', 'report'); // 操作名
        $configId = $this->request->post('config_id', null); // 配置ID，null表示使用默认配置
        
        if (!empty($_FILES['files'])) {
            $files = $_FILES['files'];
            $results = [];
            $successCount = 0;
            $failCount = 0;
            
            // 处理单个文件的情况
            if (!is_array($files['name'])) {
                $files = [
                    'name' => [$files['name']],
                    'type' => [$files['type']],
                    'tmp_name' => [$files['tmp_name']],
                    'error' => [$files['error']],
                    'size' => [$files['size']]
                ];
            }
            
            try {
                $cloudService = new \app\common\service\ScanworkCloudService($configId);
                
                foreach ($files['name'] as $k => $filename) {
                    if ($files['error'][$k] == 0) {
                        $ext = pathinfo($filename, PATHINFO_EXTENSION);
                        $allowExt = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'jfif'];
                        if (!in_array(strtolower($ext), $allowExt)) {
                            $results[] = [
                                'file' => $filename,
                                'success' => false,
                                'message' => '不支持的文件格式'
                            ];
                            $failCount++;
                            continue;
                        }
                        
                        if ($files['size'][$k] > 50 * 1024 * 1024) {
                            $results[] = [
                                'file' => $filename,
                                'success' => false,
                                'message' => '文件大小不能超过50MB'
                            ];
                            $failCount++;
                            continue;
                        }
                        
                        // 构建文件数组
                        $file = [
                            'name' => $files['name'][$k],
                            'type' => $files['type'][$k],
                            'tmp_name' => $files['tmp_name'][$k],
                            'error' => $files['error'][$k],
                            'size' => $files['size'][$k]
                        ];
                        
                        // 根据模块和操作调用不同的上传方法
                        switch ($module) {
                            case 'scanwork':
                                switch ($action) {
                                    case 'report':
                                        $result = $cloudService->uploadReportImage($file);
                                        break;
                                    case 'audit':
                                        $result = $cloudService->uploadAuditImage($file);
                                        break;
                                    case 'active_report':
                                        $result = $cloudService->uploadActiveReportImage($file);
                                        break;
                                    case 'product':
                                        $result = $cloudService->uploadProductImage($file);
                                        break;
                                    default:
                                        $result = $cloudService->uploadReportImage($file);
                                }
                                break;
                            default:
                                $result = $cloudService->uploadReportImage($file);
                        }
                        
                        if ($result['success']) {
                            $results[] = [
                                'file' => $filename,
                                'success' => true,
                                'url' => $result['url'],
                                'file_id' => $result['file_id'] ?? null,
                                'file_name' => $result['file_name'] ?? null
                            ];
                            $successCount++;
                        } else {
                            $results[] = [
                                'file' => $filename,
                                'success' => false,
                                'message' => $result['message'] ?? '未知错误'
                            ];
                            $failCount++;
                        }
                    } else {
                        $results[] = [
                            'file' => $filename,
                            'success' => false,
                            'message' => '文件上传错误'
                        ];
                        $failCount++;
                    }
                }
                
                $this->success('批量上传完成', [
                    'results' => $results,
                    'success_count' => $successCount,
                    'fail_count' => $failCount,
                    'total_count' => count($files['name'])
                ]);
                
            } catch (\Exception $e) {
                error_log('云存储API批量上传失败: ' . $e->getMessage());
                $this->error('批量上传失败：' . $e->getMessage());
            }
        } else {
            $this->error('没有选择文件');
        }
    }

    /**
     * 删除云存储文件
     */
    public function delete()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $fileId = $this->request->post('file_id');
        $fileUrl = $this->request->post('file_url');
        
        if (!$fileId && !$fileUrl) {
            $this->error('缺少文件ID或文件URL');
        }
        
        try {
            $cloudService = new \app\common\service\ScanworkCloudService();
            $result = $cloudService->deleteFile($fileId, $fileUrl);
            
            if ($result['success']) {
                $this->success('删除成功');
            } else {
                $this->error('删除失败：' . ($result['message'] ?? '未知错误'));
            }
        } catch (\Exception $e) {
            error_log('云存储API删除失败: ' . $e->getMessage());
            $this->error('删除失败：' . $e->getMessage());
        }
    }

    /**
     * 获取云存储配置列表
     */
    public function getConfigs()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        try {
            $configs = \app\admin\model\yuncunchu\Config::getEnabledConfigs();
            $configList = [];
            
            foreach ($configs as $config) {
                $configList[] = [
                    'id' => $config->id,
                    'name' => $config->name,
                    'type' => $config->type,
                    'is_default' => $config->is_default
                ];
            }
            
            $this->success('获取成功', $configList);
        } catch (\Exception $e) {
            $this->error('获取配置失败：' . $e->getMessage());
        }
    }

    /**
     * 测试云存储连接
     */
    public function testConnection()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $configId = $this->request->post('config_id');
        
        if (!$configId) {
            $this->error('缺少配置ID');
        }
        
        try {
            $config = \app\admin\model\yuncunchu\Config::find($configId);
            if (!$config) {
                $this->error('配置不存在');
            }
            
            $cloudService = new \app\common\service\ScanworkCloudService($configId);
            $result = $cloudService->testConnection();
            
            if ($result['success']) {
                $this->success('连接测试成功', $result['data']);
            } else {
                $this->error('连接测试失败：' . ($result['message'] ?? '未知错误'));
            }
        } catch (\Exception $e) {
            $this->error('连接测试失败：' . $e->getMessage());
        }
    }
}
